package com.xiguthings.waka.web.controller.useranswer;

import com.xiguthings.waka.dao.DataBaseStatus;
import com.xiguthings.waka.exception.BussinessException;
import com.xiguthings.waka.po.*;
import com.xiguthings.waka.po.extpo.Page;
import com.xiguthings.waka.publicUtils.StringUtils;
import com.xiguthings.waka.service.sysconfig.ISysConfigService;
import com.xiguthings.waka.service.user.IUserService;
import com.xiguthings.waka.service.useranswer.IUserAnswerService;
import com.xiguthings.waka.service.usershare.IUserShareService;
import com.xiguthings.waka.web.controller.base.AbstractController;
import com.xiguthings.waka.web.controller.base.ResponseEntity;
import com.xiguthings.waka.web.controller.user.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/useranswer")
@Api("/用户答卷")
public class UserAnswerController extends AbstractController {
    @Resource
    private IUserAnswerService userAnswerService;

    @Resource
    private IUserService userService;

    @Resource
    private ISysConfigService sysConfigService;


    /**
     * 创建查询条件
     *
     * @param userAnswerVo
     * @param example
     * @throws NumberFormatException
     */
    private UserAnswerExample.Criteria queryConditions(UserAnswerVo userAnswerVo, UserAnswerExample example) throws NumberFormatException {

        UserAnswerExample.Criteria criteria = example.createCriteria();
        // 如果查询条件为空的
        if (userAnswerVo == null) {
            // 则查询所有未被删除的
            criteria.andStatusNotEqualTo(DataBaseStatus.DELETE);
            return criteria;
        }

        // 如果有查询条件
        UserAnswer userAnswer = userAnswerVo.getUserAnswer();
        // 添加查询条件
        if (userAnswer != null) {
            if (StringUtils.isNotBlank(userAnswer.getUserAnswerId())) {
                criteria.andUserAnswerIdEqualTo(userAnswer.getUserAnswerId());
            }

            if (StringUtils.isNotBlank(userAnswer.getUserId())) {
                criteria.andUserIdEqualTo(userAnswer.getUserId());
            }
            if (StringUtils.isNotBlank(userAnswer.getPaperId())) {
                criteria.andPaperIdEqualTo(userAnswer.getPaperId());
            }
            if (StringUtils.isNotBlank(userAnswer.getAnswers())) {
                criteria.andAnswersLike("%" + userAnswer.getAnswers() + "%");
            }

        }


        if (StringUtils.isNotBlank(userAnswerVo.getInStatus())) {
            // 添加包含的状态
            String statuses = userAnswerVo.getInStatus();
            String[] statusArr = statuses.split(",");
            List<Integer> statusList = new ArrayList<>();
            for (String str : statusArr) {
                statusList.add(new Integer(str));
            }
            criteria.andStatusIn(statusList);
        } else {
            // 如果状态的查询条件是空的，则查询没有被删除的
            criteria.andStatusNotEqualTo(DataBaseStatus.DELETE);
        }

        return criteria;
    }


    /**
     * 修改或者添加
     *
     * @param userAnswerVo
     * @return
     * @throws Exception
     */
    @ApiOperation(tags = {
            "1.控制台"}, value = "添加答卷", httpMethod = "POST", notes = "", response = ResponseEntity.class)
    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userAnswer.userId", value = "所属的用户的主键id", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "userAnswer.paperId", value = "所属的试卷的主键id", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "userAnswer.answers", value = "选择答案的ID，每个答案之间用英文逗号分隔", dataType = "String", required = true, paramType = "query")
    })
    @RequestMapping("/add")
    @ResponseBody
    public ResponseEntity add(@ApiIgnore UserAnswerVo userAnswerVo) throws Exception {
        if (userAnswerVo == null || userAnswerVo.getUserAnswer() == null) {
            BussinessException.throwThis(CODE_EMPTY_REQUIRED, null);
        }
        UserAnswer userAnswer = userAnswerVo.getUserAnswer();
        String paperId = userAnswer.getPaperId();
        String answers = userAnswer.getAnswers();
        if (StringUtils.isBlank(paperId) || paperId.trim().equals("undefined")) {
            BussinessException.throwThis(CODE_EMPTY_REQUIRED, "请指定答题的试卷ID");
        }
        if (StringUtils.isBlank(answers)) {
            BussinessException.throwThis(CODE_EMPTY_REQUIRED, "请提交答案");
        }

        // 判断用户是否已经可以提交试卷了
        // 选获取配置中冷却的时间
        long cdTime = 0L;
        SysConfig sysConfig = sysConfigService.selectByCode(DataBaseStatus.CONFIG_CODE_USER_CD);
        if (sysConfig != null) {
            String value = sysConfig.getValue();
            cdTime = new Long(value);
        }

        User user = (User) super.getSession().getAttribute(SESSION_CRN_USER);
        String userId = null;
        if (user != null) {
            userId = user.getUserId();
            User userDB = userService.selectByPrimaryKey(userId);
            Date cdBtime = userDB.getCdBeginTime();
            Date now = new Date();// 现在时间
            if ((now.getTime() - cdBtime.getTime()) > cdTime) {
                // 现在的时间 - 用户开始冷却的时间  > 配置中设置的冷却时间    说明已经冷却完成
                userAnswer.setUserId(userId);
                userAnswerService.insert(userAnswer);
                return ajaxReturnMap(CODE_SUCCESS, null, userAnswer.getUserAnswerId());
            } else {
                return ajaxReturnMap(CODE_FAULT, "冷却时间未到", null);
            }

        }
        return ajaxReturnMap(CODE_FAULT, "用户登录过期", null);


    }

    @ApiOperation(tags = {"1.控制台",
            "2.用户端"}, value = "根据主键获取记录详情", httpMethod = "GET", notes = "userAnswerId是必填", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userAnswer.userAnswerId", value = "主键id", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "associated", value = "是否关联查询,true--关联查询,默认是false", dataType = "boolean", required = false, paramType = "query")})
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseEntity detail(@ApiIgnore UserAnswerVo userAnswerVo) throws Exception {
        if (userAnswerVo == null || userAnswerVo.getUserAnswer() == null) {
            BussinessException.throwThis(CODE_SUCCESS, null);
        }
        UserAnswer userAnswer = userAnswerVo.getUserAnswer();
        String id = userAnswer.getUserAnswerId();
        if (StringUtils.isBlank(id)) {
            BussinessException.throwThis(CODE_SUCCESS, "userAnswerId为空");
        }

        UserAnswer userAnswerDB = userAnswerService.selectByPrimaryKey(id);
        return ajaxReturnMap(CODE_SUCCESS, null, userAnswerDB);
    }


    /**
     * 分页查询
     *
     * @param userAnswerVo
     * @param page
     * @return
     * @throws Exception
     */

    @ApiOperation(tags = {"1.控制台",
            "2.用户端"}, value = "分页查询", httpMethod = "GET", notes = "可根据条件进行筛选", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userAnswer.userAnswerId", value = "主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "userAnswer.userId", value = "所属用户的ID", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "userAnswer.paperId", value = "所属的试卷的主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码，如果没有值，则使用默认值。开始值从 1 开始计算", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "rows", value = "每页的数量,如果没有值，则使用默认值", dataType = "int", required = false, paramType = "query")})
    @RequestMapping("/pagelist")
    @ResponseBody
    public ResponseEntity pageList(@ApiIgnore UserAnswerVo userAnswerVo, @ApiIgnore Page page) throws Exception {
        UserAnswerExample example = new UserAnswerExample();
        UserAnswerExample.Criteria criteria = queryConditions(userAnswerVo, example);

        User user = (User) super.getSession().getAttribute(SESSION_CRN_USER);
        if (user != null) {
            // 如果是用户端的请求，则加一个查询条件
            criteria.andUserIdEqualTo(user.getUserId());
        }
        super.selectByPage(page, example, userAnswerService);
        return ajaxReturnMap(CODE_SUCCESS, null, page);
    }

}
